import serial
import time

class RFID:
        def __init__(self,port,baud_rate):
                self.ser = serial.Serial(port,baud_rate,bytesize=8,stopbits=1)
                self.ser.flush()

        def getHexValue(self,stringHexArr):
                result = ""
                for stringHex in stringHexArr:
                        temp = stringHex.replace('0x','')
                        if(len(temp) == 1): temp = '0' + temp
                        result += temp
                return result

        def read(self,start,length):
                sentdata = []
                sentdata.append(0xBA)
                sentdata.append(0x04)
                sentdata.append(0x33)
                sentdata.append(start)
                sentdata.append(length)
                checksum = self.cal_checksum(sentdata)
                sentdata.append(checksum)
                self.ser.write(self.get_stringHex(sentdata))
                time.sleep(0.1)
                recv = []
                #self.ser.write("\xBA\x04\x33\x00\x04\x89")
                recv.append("%#x" % ord(self.ser.read()))
                while(self.ser.inWaiting()!=0):
                        recv.append("%#x" % ord(self.ser.read()))
                #Operation succeed / check sum
                if(len(recv) > 0  and int(recv[3],16) == 0 and self.cal_checksum(recv[0:-1]) == int(recv[-1:][0],16)):
                        tagID = self.getHexValue(recv[4:12])
                        productID = str(int(self.getHexValue(recv[12:16]),16)) + str(int(self.getHexValue(recv[16:20]),16))
                        print tagID
                        print productID
                        return tagID+"&&"+productID
                return ""

        def getTagInformation(self):
                self.ser.flush()
                sentdata = []
                sentdata.append(0xBA)
                sentdata.append(0x02)
                sentdata.append(0x31)
                checksum = self.cal_checksum(sentdata)
                #print hex(checksum)
                sentdata.append(checksum)
                self.ser.write(self.get_stringHex(sentdata))
                time.sleep(0.2)
                recv = []
                recv.append("%#x" % ord(self.ser.read()))
                while(self.ser.inWaiting()!=0):
                        recv.append("%#x" % ord(self.ser.read()))
                #Operation succeed / check sum
                if(len(recv) > 0  and int(recv[3],16) == 0 and self.cal_checksum(recv[0:-1]) == int(recv[-1:][0],16)):
                        tagID = self.getHexValue(recv[4:12])
                        print tagID
                        return tagID
                return ""
                
        def commandWriteTag(self,productID):
                print "############################################"
                tagid = self.getTagInformation()
                if(len(tagid) > 0):
                        firstProd = productID[0:4]
                        lastProd = productID[4:]
                        hexFirstProd = self.calculateHexValue(firstProd)
                        hexLastProd = self.calculateHexValue(lastProd)

                        preWriteData = []
                        preWriteData.append(0xBA)
                        preWriteData.append(0x07)
                        preWriteData.append(0x34)
                        preWriteData.append(0x00)       #block write
                        preWriteData.append(int(tagid[0:2],16))
                        preWriteData.append(int(tagid[2:4],16))
                        preWriteData.append(int(tagid[4:6],16))
                        preWriteData.append(int(tagid[6:8],16))
                        checksum = self.cal_checksum(preWriteData)
                        #print hex(checksum)
                        preWriteData.append(checksum)
                        if(not self.writeTag(preWriteData)):
                                return False
                        #time.sleep(0.3)

                        preWriteData = []
                        preWriteData.append(0xBA)
                        preWriteData.append(0x07)
                        preWriteData.append(0x34)
                        preWriteData.append(0x01)       #block write
                        preWriteData.append(int(tagid[8:10],16))
                        preWriteData.append(int(tagid[10:12],16))
                        preWriteData.append(int(tagid[12:14],16))
                        preWriteData.append(int(tagid[14:16],16))
                        checksum = self.cal_checksum(preWriteData)
                        preWriteData.append(checksum)
                        if(not self.writeTag(preWriteData)):
                                return False
                        #time.sleep(0.3)

                        preWriteData = []
                        preWriteData.append(0xBA)
                        preWriteData.append(0x07)
                        preWriteData.append(0x34)
                        preWriteData.append(0x02)       #block write
                        preWriteData.append(0x00)
                        preWriteData.append(0x00)
                        preWriteData.append(int(hexFirstProd[0:4],16))
                        preWriteData.append(int(hexFirstProd[4:],16))
                        checksum = self.cal_checksum(preWriteData)
                        preWriteData.append(checksum)
                        if(not self.writeTag(preWriteData)):
                                return False
                        #time.sleep(0.3)

                        preWriteData = []
                        preWriteData.append(0xBA)
                        preWriteData.append(0x07)
                        preWriteData.append(0x34)
                        preWriteData.append(0x03)       #block write
                        preWriteData.append(int(hexLastProd[0:4],16))
                        preWriteData.append(int(hexLastProd[4:6],16))
                        preWriteData.append(int(hexLastProd[6:8],16))
                        preWriteData.append(int(hexLastProd[8:],16))
                        checksum = self.cal_checksum(preWriteData)
                        preWriteData.append(checksum)
                        if(not self.writeTag(preWriteData)):
                                return False
                        #time.sleep(0.5)

                        return True

        def writeTag(self,data):
                print "============start write================"
                self.ser.write(self.get_stringHex(data))
                recv = []
                time.sleep(0.1)
                recv.append("%#x" % ord(self.ser.read()))
                #print "%#x" % ord(recvHeader)
                while(self.ser.inWaiting()!=0):
                        recv.append("%#x" % ord(self.ser.read()))
                        #print "%#x" % ord(self.ser.read())
                if(len(recv) > 0  and int(recv[3],16) == 0 and self.cal_checksum(recv[0:-1]) == int(recv[-1:][0],16)): return True
                else: return False
                print "============end write================"

	
        def close(self):
                self.ser.close()

        def cal_checksum(self,calculate_data):
                result = 0x00
                for i in calculate_data:
                        if(isinstance(i,str)) : result = result^int(i,16)
                        else : result = result^i
                return result

        def get_stringHex(self,data):
                result = ""
                for i in data:
                        result += chr(i)                
                return result
        
        def calculateHexValue(self,data):
                temp = hex(int(data))[2:]
                while (len(temp)<8 and len(temp)!=4):
                        temp = "0"+temp
                return "0x"+temp

#x = RFID('/dev/ttyUSB0',115200)
#x.getTagInformation()
#x.read(0,4)
#while(True):
        #print "sent"
        #if(x.commandWriteTag("8856129001174")) : break
